﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XTools.XToolsBLLEx;
namespace XTools.App_Code
{
    /// <summary>
    /// 界面数据处理
    /// </summary>
    public class DgvOperate
    {
        /// <summary>
        /// 生成站点信息--按全部写入
        /// </summary>
        public byte[] CreateStationsInfo(DataGridView Cm10Dgv, DataGridView Cm11Dgv, DataGridView Cm12Dgv, DataGridView C0Dgv, DataGridView CxDgv, Dictionary<int, List<object>> dicXuYuan)
        {
            int arrLength = 0;
            arrLength += Convert.ToInt32(Cm10Dgv.Rows[1].Cells["属性"].Value.ToString());
            arrLength += Convert.ToInt32(Cm11Dgv.Rows[1].Cells["属性"].Value.ToString());
            arrLength += Convert.ToInt32(Cm12Dgv.Rows[1].Cells["属性"].Value.ToString());
            for (int i = 0; i < C0Dgv.Rows.Count; i++)
            {
                arrLength += Convert.ToInt32(C0Dgv.Rows[i].Cells["域长度"].Value.ToString());
            }
            foreach (KeyValuePair<int, List<object>> kv in dicXuYuan)
            {
                List<object> list = kv.Value;

                for (int i = 0; i < list.Count; i++)
                {
                    DataGridViewRow row = (DataGridViewRow)list[i];

                    arrLength += Convert.ToInt32(row.Cells[1].Value);
                }
            }

            byte[] bytes = new byte[arrLength * 64];
            int index = 0;

            ReadCm(ref bytes, ref index, Cm10Dgv);
            ReadCm(ref bytes, ref index, Cm11Dgv);
            ReadCm(ref bytes, ref index, Cm12Dgv);
            ReadC0(ref bytes, ref index, C0Dgv, CxDgv, dicXuYuan, 0, 1);
            string szBytes = FormatHelper.ByteToStringEx(bytes);
            string result = StationManageEx.OrderCfg(szBytes,0);
            byte[] ByteResult = FormatHelper.StringToByte(result);
            return ByteResult;
        }

        /// <summary>
        /// 读取主元数据
        /// </summary>
        private byte[] ReadCm(ref byte[] des, ref int index, DataGridView dgv)
        {
            StringBuilder str = new StringBuilder("");
            int dgvRowsCount = dgv.Rows.Count;

            string bitStartPosition = "";
            string bitMsg = "";

            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                DataGridViewRow row = dgv.Rows[i];
                string value = "";
                if (row.Cells["属性"].Value != null)
                {
                    value = row.Cells["属性"].Value.ToString();
                }

                int startPosition = Convert.ToInt32(FormatHelper.hex2dec(row.Cells["START_POSITION"].Value.ToString()));

                /*当前字段起始位置：64字节起点位置，补0*/
                if (startPosition % 64 == 0 && startPosition != 0)
                {
                    int length = str.Length;
                    int remainder = (length / 2) % 64;
                    if (remainder != 0)
                    {
                        for (int j = 0; j < 64 - remainder; j++)
                        {
                            des[index] = 0;
                            str.Append("00");
                            index++;
                        }
                    }
                }

                int type = FormatHelper.FieldType(row.Cells["TYPE"].Value.ToString());
                if (row.Cells["TEXT_PianYiAdder"].Value.ToString().ToUpper() != "F")
                {
                    if (value == "") value = "0";
                    if (type == 1)
                    {
                        value = FormatHelper.DecimalToBinary(Convert.ToInt32(value), Convert.ToInt32(row.Cells["LENGTH"].Value.ToString()));
                    }
                    else if (type == 2)
                    {
                        value = FormatHelper.HexToBinary(value, Convert.ToInt32(row.Cells["LENGTH"].Value.ToString()));
                    }
                    type = 4;
                }
               
                if (type == 4)
                {
                    bitStartPosition = startPosition.ToString();

                    int length = Convert.ToInt32(row.Cells["LENGTH"].Value.ToString());
                    while (value.Length < length)
                    {
                        value = "0" + value;
                    }
                    bitMsg = value + bitMsg;
                }
                else
                {
                    if (type == 2)
                    {
                        value = value.TrimStart("&H".ToCharArray());
                    }//当链接类型为空时，不生成默认数据
                    if (!(type == 5 && value.Trim() == ""))
                    {
                        FormatHelper.ToBytes(value, ref des, ref index, Convert.ToInt32(row.Cells["LENGTH"].Value.ToString()), row.Cells["TYPE"].Value.ToString());
                        str.Append(FormatHelper.ToHex(value, row.Cells["TYPE"].Value.ToString(), row.Cells["LENGTH"].Value.ToString()));
                    }
                }

                /*当前字段：最后一个，补0*/
                if (dgvRowsCount == (i + 1))
                {
                    if (bitStartPosition != "")
                    {
                        FormatHelper.ToBytes(bitMsg, ref des, ref index, 1, "bit");
                        str.Append(FormatHelper.ToHex(bitMsg, "bit", "1"));
                        bitStartPosition = "";
                        bitMsg = "";
                    }

                    int length = str.Length;
                    int remainder = (length / 2) % 64;
                    if (remainder != 0)
                    {
                        for (int j = 0; j < 64 - remainder; j++)
                        {
                            des[index] = 0;
                            str.Append("00");
                            index++;
                        }
                    }
                }
                else
                {
                    //获取下一个字段首地址
                    string nextStartPosition = FormatHelper.hex2dec(dgv.Rows[i + 1].Cells["START_POSITION"].Value.ToString());
                    if (bitStartPosition != "" && bitStartPosition != nextStartPosition)
                    {
                        FormatHelper.ToBytes(bitMsg, ref des, ref index, 1, "bit");
                        str.Append(FormatHelper.ToHex(bitMsg, "bit", "1"));
                        bitStartPosition = "";
                        bitMsg = "";
                    }
                }
            }

            return des;
        }

        /// <summary>
        /// 读取基元数据
        /// </summary>
        private byte[] ReadC0(ref byte[] des, ref int index, DataGridView dgv, DataGridView CxDgv, Dictionary<int, List<object>> dicXuYuan, int t, int num)
        {
            StringBuilder str = new StringBuilder("");
            int dgvColumnsCount = dgv.Columns.Count - num;

            string bitStartPosition = "";
            string bitMsg = "";

            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                StringBuilder strC0 = new StringBuilder("");
                DataGridViewRow row = dgv.Rows[i];

                // 排除最后一个字段“编号”
                for (int j = 0; j < dgv.Columns.Count - num; j++)
                {
                    DataGridViewColumn column = dgv.Columns[j];
                    string[] columns = column.Tag.ToString().Split('|');

                    string value = "";
                    if (row.Cells[j].Value != null)
                    {
                        value = row.Cells[j].Value.ToString();
                    }

                    int startPosition = Convert.ToInt32(FormatHelper.hex2dec(columns[0]));

                    /*当前字段起始位置：64字节起点位置，补0*/
                    if (startPosition % 64 == 0 && startPosition != 0)
                    {
                        int length = strC0.Length;
                        int remainder = (length / 2) % 64;
                        if (remainder != 0)
                        {
                            for (int m = 0; m < 64 - remainder; m++)
                            {
                                des[index] = 0;
                                strC0.Append("00");
                                index++;
                            }
                        }
                    }

                    int type = FormatHelper.FieldType(columns[2]);
                    if (columns[6].ToUpper() != "F")
                    {
                        if (value == "") value = "0";
                        if (type == 1)
                        {
                            value = FormatHelper.DecimalToBinary(Convert.ToInt32(value), Convert.ToInt32(columns[1]));
                        }
                        else if (type == 2)
                        {
                            value = FormatHelper.HexToBinary(value, Convert.ToInt32(columns[1]));
                        }
                        type = 4;
                    }
                    if (type == 4)
                    {
                        bitStartPosition = startPosition.ToString();

                        int length = Convert.ToInt32(columns[1]);
                        while (value.Length < length)
                        {
                            value = "0" + value;
                        }
                        bitMsg = value + bitMsg;
                    }
                    else
                    {
                        if (type == 2)
                        {
                            value = value.TrimStart("&H".ToCharArray());
                        }
                        //当链接类型为空时，不生成默认数据
                        if (!(type == 5 && value.Trim() == ""))
                        {
                            FormatHelper.ToBytes(value, ref des, ref index, Convert.ToInt32(columns[1]), columns[2]);
                            strC0.Append(FormatHelper.ToHex(value, columns[2], columns[1]));
                        }
                    }

                    /*当前字段：最后一个，补0*/
                    if (dgvColumnsCount == (j + 1))
                    {
                        if (bitStartPosition != "")
                        {
                            FormatHelper.ToBytes(bitMsg, ref des, ref index, 1, "bit");
                            strC0.Append(FormatHelper.ToHex(bitMsg, "bit", "1"));
                            bitStartPosition = "";
                            bitMsg = "";
                        }

                        int length = strC0.Length;
                        int remainder = (length / 2) % 64;
                        if (remainder != 0)
                        {
                            for (int m = 0; m < 64 - remainder; m++)
                            {
                                des[index] = 0;
                                strC0.Append("00");
                                index++;
                            }
                        }
                    }
                    else
                    {
                        //获取下一个字段首地址
                        string nextStartPosition = FormatHelper.hex2dec(dgv.Columns[j + 1].Tag.ToString().Split('|')[0]);
                        if (bitStartPosition != "" && bitStartPosition != nextStartPosition)
                        {
                            FormatHelper.ToBytes(bitMsg, ref des, ref index, 1, "bit");
                            strC0.Append(FormatHelper.ToHex(bitMsg, "bit", "1"));
                            bitStartPosition = "";
                            bitMsg = "";
                        }
                    }
                }

                if (t == 0)
                {
                    if (dicXuYuan.Keys.Contains(Convert.ToInt32(row.Cells[dgvColumnsCount].Value.ToString())))
                    {
                        ReadCx(ref des, ref index, CxDgv, dicXuYuan[Convert.ToInt32(row.Cells[dgvColumnsCount].Value.ToString())]);
                    }
                }
            }
            return des;
        }

        /// <summary>
        /// 读取虚元数据
        /// </summary>
        private byte[] ReadCx(ref byte[] des, ref int index, DataGridView dgv, List<object> list)
        {
            StringBuilder str = new StringBuilder("");
            int dgvColumnsCount = dgv.Columns.Count - 2;

            string bitStartPosition = "";
            string bitMsg = "";

            for (int i = 0; i < list.Count; i++)
            {
                StringBuilder strCx = new StringBuilder("");
                DataGridViewRow row = (DataGridViewRow)list[i];

                // 排除最后两个字段“编号”、“基元编号”
                for (int j = 0; j < dgv.Columns.Count - 2; j++)
                {
                    DataGridViewColumn column = dgv.Columns[j];
                    string[] columns = column.Tag.ToString().Split('|');

                    string value = "";
                    if (row.Cells[j].Value != null)
                    {
                        value = row.Cells[j].Value.ToString();
                    }

                    int startPosition = Convert.ToInt32(FormatHelper.hex2dec(columns[0]));

                    /*当前字段起始位置：64字节起点位置，补0*/
                    if (startPosition % 64 == 0 && startPosition != 0)
                    {
                        int length = strCx.Length;
                        int remainder = (length / 2) % 64;
                        if (remainder != 0)
                        {
                            for (int m = 0; m < 64 - remainder; m++)
                            {
                                des[index] = 0;
                                strCx.Append("00");
                                index++;
                            }
                        }
                    }

                    int type = FormatHelper.FieldType(columns[2]);
                    if (columns[6].ToUpper() != "F")
                    {
                        if (value == "") value = "0";
                        if (type == 1)
                        {
                            value = FormatHelper.DecimalToBinary(Convert.ToInt32(value), Convert.ToInt32(columns[1]));
                        }
                        else if (type == 2)
                        {
                            value = FormatHelper.HexToBinary(value, Convert.ToInt32(columns[1]));
                        }
                        type = 4;
                    }

                    if (type == 4)
                    {
                        bitStartPosition = startPosition.ToString();

                        int length = Convert.ToInt32(columns[1]);
                        while (value.Length < length)
                        {
                            value = "0" + value;
                        }
                        bitMsg = value + bitMsg;
                    }
                    else
                    {
                        if (type == 2)
                        {
                            value = value.TrimStart("&H".ToCharArray());
                        }
                        //当链接类型为空时，不生成默认数据
                        if (!(type == 5 && value.Trim() == ""))
                        {
                            FormatHelper.ToBytes(value, ref des, ref index, Convert.ToInt32(columns[1]), columns[2]);
                            strCx.Append(FormatHelper.ToHex(value, columns[2], columns[1]));
                        }
                    }

                    /*当前字段：最后一个，补0*/
                    if (dgvColumnsCount == (j + 1))
                    {
                        if (bitStartPosition != "")
                        {
                            FormatHelper.ToBytes(bitMsg, ref des, ref index, 1, "bit");
                            strCx.Append(FormatHelper.ToHex(bitMsg, "bit", "1"));
                            bitStartPosition = "";
                            bitMsg = "";
                        }

                        int length = strCx.Length;
                        int remainder = (length / 2) % 64;
                        if (remainder != 0)
                        {
                            for (int m = 0; m < 64 - remainder; m++)
                            {
                                des[index] = 0;
                                strCx.Append("00");
                                index++;
                            }
                        }
                    }
                    else
                    {
                        //获取下一个字段首地址
                        string nextStartPosition = FormatHelper.hex2dec(dgv.Columns[j + 1].Tag.ToString().Split('|')[0]);
                        if (bitStartPosition != "" && bitStartPosition != nextStartPosition)
                        {
                            FormatHelper.ToBytes(bitMsg, ref des, ref index, 1, "bit");
                            strCx.Append(FormatHelper.ToHex(bitMsg, "bit", "1"));
                            bitStartPosition = "";
                            bitMsg = "";
                        }
                    }
                }
            }
            return des;
        }

        /// <summary>
        /// 设置 业务包长度 正文校验
        /// </summary>
        public static byte[] PacketBytes(byte[] bytes, byte mapType, string cfg_crc, string cfg_index, byte[] spackBytes)
        {
            byte[] returnBytes;
            //特例：当MapType=MAP_CFG时，终端根据bitDO_CFG_CRC决定是否需要CFG进行CRC校验。
            if (mapType == Constants.OP_DEFAULT)
            {
                returnBytes = new byte[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + Constants.LEN_CFG_INDEX + bytes.Length + Constants.LEN_CRC];

                //设置业务包长度
                byte[] lenPackBytes = BitConverter.GetBytes(spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + Constants.LEN_CFG_INDEX + bytes.Length);
                returnBytes[0] = lenPackBytes[0];
                returnBytes[1] = lenPackBytes[1];

                //拷贝可选字符
                for (int i = 0; i < spackBytes.Length; i++)
                {
                    returnBytes[i + Constants.LEN_LENPACK] = spackBytes[i];
                }
             
                //设置结束字符
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length] = 0;

                //设置CFG_CRC
                int cfgCrc = Convert.ToInt32(cfg_crc, 16);
                byte[] cfgCrcBytes = BitConverter.GetBytes(cfgCrc);
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END] = cfgCrcBytes[0];
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + 1] = cfgCrcBytes[1];

                //设置CfgIndex
                int cfgIndex = Convert.ToInt32(cfg_index, 16);
                byte[] cfgIndexBytes = BitConverter.GetBytes(cfgIndex);
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC] = cfgIndexBytes[0];
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + 1] = cfgIndexBytes[1];

                //拷贝报文
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnBytes[i + Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + Constants.LEN_CFG_INDEX] = bytes[i];
                }

                //设置CRC
                long crc = Constants.GetCrc(returnBytes, 0, Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + Constants.LEN_CFG_INDEX + bytes.Length);
                byte[] crcBytes = BitConverter.GetBytes(crc);
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + Constants.LEN_CFG_INDEX + bytes.Length] = crcBytes[0];
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CFG_CRC + Constants.LEN_CFG_INDEX + bytes.Length + 1] = crcBytes[1];
            }
            else
            {
                returnBytes = new byte[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + bytes.Length + Constants.LEN_CRC];

                //设置业务包长度
                byte[] lenPackBytes = BitConverter.GetBytes(spackBytes.Length + Constants.LEN_END + bytes.Length);
                returnBytes[0] = lenPackBytes[0];
                returnBytes[1] = lenPackBytes[1];

                //拷贝可选字符
                for (int i = 0; i < spackBytes.Length; i++)
                {
                    returnBytes[i + Constants.LEN_LENPACK] = spackBytes[i];
                }

                //设置结束字符
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length] = 0;

                //拷贝报文
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnBytes[i + Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END] = bytes[i];
                }

                //设置CRC
                long crc = Constants.GetCrc(returnBytes, 0, Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + bytes.Length);
                byte[] crcBytes = BitConverter.GetBytes(crc);
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + bytes.Length] = crcBytes[0];
                returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + bytes.Length + 1] = crcBytes[1];
            }

            return returnBytes;
        }

        /// <summary>
        /// 设置 业务包长度 正文校验
        /// </summary>
        public static byte[] PacketBytes(byte[] spackBytes)
        {
            byte[] returnBytes = new byte[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + Constants.LEN_CRC];

            //设置业务包长度
            byte[] lenPackBytes = BitConverter.GetBytes(spackBytes.Length + Constants.LEN_END);
            returnBytes[0] = lenPackBytes[0];
            returnBytes[1] = lenPackBytes[1];

            //拷贝可选字符
            for (int i = 0; i < spackBytes.Length; i++)
            {
                returnBytes[i + Constants.LEN_LENPACK] = spackBytes[i];
            }

            //设置结束字符
            returnBytes[Constants.LEN_LENPACK + spackBytes.Length] = 0;

            //设置CRC
            long crc = Constants.GetCrc(returnBytes, 0, Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END);
            byte[] crcBytes = BitConverter.GetBytes(crc);
            returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END] = crcBytes[0];
            returnBytes[Constants.LEN_LENPACK + spackBytes.Length + Constants.LEN_END + 1] = crcBytes[1];

            return returnBytes;
        }

        /// <summary>
        /// 数据换行
        /// </summary>
        public static string SpreadByte(string strStation)
        {
            string C10 = "";
            string C11 = "";
            string C12 = "";
            string[] C0Cx = new string[0xff];
            int index = 0;
            int lenC10 = Convert.ToInt32(strStation.Substring(Constants.POS_C10_C11_C12 * 2, Constants.LEN_C10_C11_C12 * 2), 16);
            C10 = strStation.Substring(0, lenC10 * 64 * 2);//基本域
            strStation = strStation.Substring(lenC10 * 64 * 2);

            int lenC11 = Convert.ToInt32(strStation.Substring(Constants.POS_C10_C11_C12 * 2, Constants.LEN_C10_C11_C12 * 2), 16);
            C11 = strStation.Substring(0, lenC11 * 64 * 2);//扩展域
            strStation = strStation.Substring(lenC11 * 64 * 2);

            int lenC12 = Convert.ToInt32(strStation.Substring(Constants.POS_C10_C11_C12 * 2, Constants.LEN_C10_C11_C12 * 2), 16);
            C12 = strStation.Substring(0, lenC12 * 64 * 2);//通信域
            strStation = strStation.Substring(lenC12 * 64 * 2);

            bool isCorrect = true;
            while (isCorrect && strStation != "")
            {
                try
                {
                    if (strStation.StartsWith("2") || strStation.StartsWith("3"))//基元
                    {
                        int lenTemp = Convert.ToInt32(strStation.Substring(Constants.POS_C0 * 2, Constants.LEN_C0 * 2), 16);
                        C0Cx[index++] = strStation.Substring(0, lenTemp * 64 * 2);
                        strStation = strStation.Substring(lenTemp * 64 * 2);
                    }
                    else if (strStation.StartsWith("4") || strStation.StartsWith("5") || strStation.StartsWith("6") || strStation.StartsWith("7"))//虚元
                    {
                        int lenTemp = Convert.ToInt32(strStation.Substring(Constants.POS_CX * 2, Constants.LEN_CX * 2), 16);
                        C0Cx[index++] = strStation.Substring(0, lenTemp * 64 * 2);
                        strStation = strStation.Substring(lenTemp * 64 * 2);
                    }
                    else
                    {
                        isCorrect = false;
                    }
                }
                catch (Exception)
                {
                    isCorrect = false;
                }
            }

            strStation = C10 + "\r\n" + C11 + "\r\n" + C12;

            for (int i = 0; i < C0Cx.Length; i++)
            {
                strStation += "\r\n" + C0Cx[i];
            }

            //strStation = StationOpera.ReviseStation(strStation);

            return strStation;
        }

        //判断单元格是否连续
        public static bool CheckSelectedCell(DataGridView dgv, int focus, ref int errType)
        {
            List<int> ListIndex = new List<int>();
            int RowIdex = -1;
            int ColIdex = -1;
            //基元 虚元
            if (focus == 1 || focus == 2)
            {
                foreach (DataGridViewCell cell in dgv.SelectedCells)
                {
                    if (RowIdex == -1)
                    {
                        RowIdex = cell.RowIndex;
                        ListIndex.Add(cell.ColumnIndex);
                    }
                    else
                    {
                        if (RowIdex != cell.RowIndex)
                        {
                            return false;
                        }
                        ListIndex.Add(cell.ColumnIndex);
                    }
                }

                ListIndex.Sort();

                for (int i = 0; i < ListIndex.Count - 1; i++)
                {
                    if (ListIndex[i] != ListIndex[i + 1] - 1)
                    {
                        return false;
                    }
                }

                return true;
            }
            //主元
            else if (focus == 10 || focus == 11 || focus == 12)
            {
                foreach (DataGridViewCell cell in dgv.SelectedCells)
                {
                    if (cell.ColumnIndex != 1)
                    {
                        continue;
                    }
                    if (ColIdex == -1)
                    {
                        ColIdex = cell.ColumnIndex;
                        ListIndex.Add(cell.RowIndex);
                    }
                    else
                    {
                        ListIndex.Add(cell.RowIndex);
                    }
                }

                ListIndex.Sort();

                for (int i = 0; i < ListIndex.Count - 1; i++)
                {
                    if (ListIndex[i] != ListIndex[i + 1] - 1)
                    {
                        return false;
                    }
                }

                if (ListIndex.Count == 0)
                {
                    errType = 1;
                    return false;
                }

                return true;
            }
            return false;
        }

        //获取起点位置、字节数
        public static void GetSelectedCell(DataGridView dgv, int focus, ref int pos, ref int len)
        {
            List<int> ListIndex = new List<int>();
            int RowIdex = -1;
            int ColIdex = -1;
            //基元 虚元
            if (focus == 1 || focus == 2)
            {
                foreach (DataGridViewCell cell in dgv.SelectedCells)
                {
                    if (RowIdex == -1)
                    {
                        RowIdex = cell.RowIndex;
                        ListIndex.Add(cell.ColumnIndex);
                    }
                    else
                    {
                        ListIndex.Add(cell.ColumnIndex);
                    }
                }

                ListIndex.Sort();

                if (ListIndex.Count == 0)
                {
                    return;
                }

                int tempStartPosition = 0;
                int tempLength = 0;

                for (int i = ListIndex[0]; i <= ListIndex[ListIndex.Count - 1]; i++)
                {
                    string[] tags = dgv.Columns[i].Tag.ToString().Split('|');
                    if (i == ListIndex[0])
                    {
                        pos = Convert.ToInt32(tags[0], 16);
                    }

                    int startPosition = Convert.ToInt32(FormatHelper.hex2dec(tags[0]));

                    /*当前字段起始位置：64字节起点位置，前面补长度*/
                    if (startPosition % 64 == 0 && startPosition != 0)
                    {
                        if (tempStartPosition != 0 && tempLength != 0)
                        {
                            int remainder = (tempStartPosition + tempLength) % 64;
                            if (remainder != 0)
                            {
                                len += 64 - remainder;
                            }
                        }
                    }

                    tempStartPosition = startPosition;

                    if (tags[2] == "字符串" || tags[2] == "十进制" || tags[2] == "十六进制" || tags[2] == "浮点型")
                    {
                        tempLength = Convert.ToInt32(tags[1]);
                        len += tempLength;
                    }
                    else if (tags[2] == "bit")
                    {
                        /*当前字段：最后一个*/
                        if (i == ListIndex[ListIndex.Count - 1])
                        {
                            tempLength = 1;
                            len += tempLength;
                        }
                        else
                        {
                            //获取下一个字段首地址
                            int nextStartPosition = Convert.ToInt32(FormatHelper.hex2dec(dgv.Columns[i + 1].Tag.ToString().Split('|')[0]));
                            if (startPosition != nextStartPosition)
                            {
                                tempLength = 1;
                                len += tempLength;
                            }
                        }
                    }
                    else if (tags[2] == "链接")
                    {
                        string str = FormatHelper.str2hex(dgv.Rows[RowIdex].Cells[i].Value.ToString(), "gbk", false);

                        if (str.Length % (64 * 2) == 0 && str.Length != 0)
                        {
                            string last_str = str.Substring(str.Length - 2, 2);

                            if (last_str != "00")
                            {
                                for (int j = 0; j < 64; j++)
                                {
                                    str += "00";
                                }
                            }
                        }

                        byte[] linkArr = FormatHelper.StringToByte(str);
                        //获取该字段所需域长度
                        if (linkArr.Length % 64 != 0)
                        {
                            tempLength = (linkArr.Length / 64 + 1) * 64;
                            len += tempLength;
                        }
                        else
                        {
                            tempLength = linkArr.Length;
                            len += tempLength;
                        }
                    }
                }
            }
            //主元
            else if (focus == 10 || focus == 11 || focus == 12)
            {
                foreach (DataGridViewCell cell in dgv.SelectedCells)
                {
                    if (cell.ColumnIndex != 1)
                    {
                        continue;
                    }
                    if (ColIdex == -1)
                    {
                        ColIdex = cell.ColumnIndex;
                        ListIndex.Add(cell.RowIndex);
                    }
                    else
                    {
                        ListIndex.Add(cell.RowIndex);
                    }
                }

                ListIndex.Sort();

                if (ListIndex.Count == 0)
                {
                    return;
                }

                int tempStartPosition = 0;
                int tempLength = 0;

                for (int i = ListIndex[0]; i <= ListIndex[ListIndex.Count - 1]; i++)
                {
                    int Len = Convert.ToInt32(dgv.Rows[i].Cells["LENGTH"].Value.ToString().Trim('.'));
                    string START_POSITION = dgv.Rows[i].Cells["START_POSITION"].Value.ToString();
                    string Type = dgv.Rows[i].Cells["TYPE"].Value.ToString();

                    if (i == ListIndex[0])
                    {
                        pos = Convert.ToInt32(START_POSITION, 16);
                    }

                    int startPosition = Convert.ToInt32(FormatHelper.hex2dec(START_POSITION));

                    /*当前字段起始位置：64字节起点位置，前面补长度*/
                    if (startPosition % 64 == 0 && startPosition != 0)
                    {
                        if (tempStartPosition != 0 && tempLength != 0)
                        {
                            int remainder = (tempStartPosition + tempLength) % 64;
                            if (remainder != 0)
                            {
                                len += 64 - remainder;
                            }
                        }
                    }

                    tempStartPosition = startPosition;

                    if (Type == "字符串" || Type == "十进制" || Type == "十六进制" || Type == "浮点型")
                    {
                        tempLength = Len;
                        len += tempLength;
                    }
                    else if (Type == "bit")
                    {
                        /*当前字段：最后一个*/
                        if (i == ListIndex[ListIndex.Count - 1])
                        {
                            tempLength = 1;
                            len += tempLength;
                        }
                        else
                        {
                            //获取下一个字段首地址
                            int nextStartPosition = Convert.ToInt32(FormatHelper.hex2dec(dgv.Rows[i + 1].Cells["START_POSITION"].Value.ToString()));
                            if (startPosition != nextStartPosition)
                            {
                                tempLength = 1;
                                len += tempLength;
                            }
                        }
                    }
                    else if (Type == "链接")
                    {
                        string str = FormatHelper.str2hex(dgv.Rows[i].Cells["属性"].Value.ToString(), "gbk", false);

                        if (str.Length % (64 * 2) == 0 && str.Length != 0)
                        {
                            string last_str = str.Substring(str.Length - 2, 2);

                            if (last_str != "00")
                            {
                                for (int j = 0; j < 64; j++)
                                {
                                    str += "00";
                                }
                            }
                        }

                        byte[] linkArr = FormatHelper.StringToByte(str);
                        //获取该字段所需域长度
                        if (linkArr.Length % 64 != 0)
                        {
                            tempLength = (linkArr.Length / 64 + 1) * 64;
                            len += tempLength;
                        }
                        else
                        {
                            tempLength = linkArr.Length;
                            len += tempLength;
                        }
                    }
                }
            }
        }

        //获取该字段前面所有长度
        public static long GetStartPos(DataGridView Cm10Dgv, DataGridView Cm11Dgv, DataGridView Cm12Dgv, DataGridView C0Dgv, DataGridView CxDgv, Dictionary<int, List<object>> dicXuYuan, int focus)
        {
            long pos = 0;

            //主元域长
            int len10 = Convert.ToInt32(Cm10Dgv.Rows[Constants.COL_C10_C11_C12_LEN].Cells["属性"].Value.ToString());
            int len11 = Convert.ToInt32(Cm11Dgv.Rows[Constants.COL_C10_C11_C12_LEN].Cells["属性"].Value.ToString());
            int len12 = Convert.ToInt32(Cm12Dgv.Rows[Constants.COL_C10_C11_C12_LEN].Cells["属性"].Value.ToString());

            //基元域长
            int[] lenC0 = new int[C0Dgv.Rows.Count];
            for (int i = 0; i < C0Dgv.Rows.Count; i++)
            {
                lenC0[i] = Convert.ToInt32(C0Dgv.Rows[i].Cells[Constants.COL_C0_LEN].Value.ToString());
            }
            
            //虚元域长
            int[][] lenCx = new int[C0Dgv.Rows.Count][];
            for (int i = 0; i < C0Dgv.Rows.Count; i++)
            {
                int RowId = Convert.ToInt32(C0Dgv.Rows[i].Cells["编号"].Value.ToString());
                lenCx[i] = new int[dicXuYuan[RowId].Count];
                for (int j = 0; j < dicXuYuan[RowId].Count; j++)
                {
                    lenCx[i][j] = Convert.ToInt32(((DataGridViewRow)dicXuYuan[RowId][j]).Cells[Constants.COL_CX_LEN].Value.ToString());
                }
            }
            
            int C0Idex = -1;//基元编号
            int CxIdex = -1;//虚元编号
            if (focus == 1)
            {
                foreach (DataGridViewCell cell in C0Dgv.SelectedCells)
                {
                    if (C0Idex == -1)
                    {
                        C0Idex = cell.RowIndex;
                        break;
                    }
                }
            }
            else if (focus == 2)
            {
                foreach (DataGridViewCell cell in CxDgv.SelectedCells)
                {
                    if (C0Idex == -1)
                    {
                        C0Idex = Convert.ToInt32(CxDgv.Rows[cell.RowIndex].Cells["基元编号"].Value.ToString());
                        CxIdex = cell.RowIndex;
                        break;
                    }
                }
            }

            switch (focus)
            {
                case 1:
                    pos += len10;
                    pos += len11;
                    pos += len12;
                    for (int i = 0; i < C0Idex; i++)
                    {
                        pos += lenC0[i];
                        for (int j = 0; j < lenCx[i].Length; j++)
                        {
                            pos += lenCx[i][j];
                        }
                    }
                    break;
                case 2:
                    pos += len10;
                    pos += len11;
                    pos += len12;
                    for (int i = 0; i < C0Dgv.Rows.Count; i++)
                    {
                        if (Convert.ToInt32(C0Dgv.Rows[i].Cells["编号"].Value.ToString()) < C0Idex)
                        {
                            pos += lenC0[i];
                            for (int j = 0; j < lenCx[i].Length; j++)
                            {
                                pos += lenCx[i][j];
                            }
                        }
                        else if (Convert.ToInt32(C0Dgv.Rows[i].Cells["编号"].Value.ToString()) == C0Idex)
                        {
                            pos += lenC0[i];
                            for (int j = 0; j < CxIdex; j++)
                            {
                                pos += lenCx[i][j];
                            }
                        }
                    }
                    break;
                case 10:
                    pos = 0;
                    break;
                case 11:
                    pos += len10;
                    break;
                case 12:
                    pos += len10;
                    pos += len11;
                    break;
                case 0://获取全部页数
                    pos += len10;
                    pos += len11;
                    pos += len12;
                    for (int i = 0; i < lenC0.Length; i++)
                    {
                        pos += lenC0[i];
                        for (int j = 0; j < lenCx[i].Length; j++)
                        {
                            pos += lenCx[i][j];
                        }
                    }
                    break;
                default:
                    return -1;
            }
            return pos;
        }

        //获取选中数据
        public byte[] GetSelectedCellValue(DataGridView dgv, long PageIndex, int Pages, int focus)
        {
            int arrLength = 0;
            byte[] bytes = null;
            byte[] newBytes = new byte[Pages];
            int index = 0;
            int pos = 0;

            if (focus == 1 || focus == 2)
            {
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    arrLength += Convert.ToInt32(dgv.Rows[i].Cells["域长度"].Value.ToString());
                }
                bytes = new byte[arrLength * 64];
                ReadC0(ref bytes, ref index, dgv, null, null, 1, focus);

                int rowIndex = dgv.SelectedCells[0].RowIndex;
                for (int i = 0; i < rowIndex; i++)
                {
                    pos += Convert.ToInt32(dgv.Rows[i].Cells["域长度"].Value.ToString());
                }
            }
            else if (focus == 10 || focus == 11 || focus == 12)
            {
                arrLength = Convert.ToInt32(dgv.Rows[1].Cells["属性"].Value.ToString());
                bytes = new byte[arrLength * 64];
                ReadCm(ref bytes, ref index, dgv);
            }

            int c = 0;
            for (long i = PageIndex + pos * 64; i < PageIndex + Pages + pos * 64; i++)
            {
                newBytes[c] = bytes[i];
                c++;
            }

            return newBytes;
        }
    }
}